/*
** window.c for  in /home/guicqu_g//rush/epikong/etape_1
** 
** Made by gallien guicquero
** Login   <guicqu_g@epitech.net>
** 
** Started on  Fri Mar 25 21:13:26 2011 gallien guicquero
** Last update Sat Mar 26 13:51:09 2011 gallien guicquero
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "mlx.h"
#include "window.h"
#include "map.h"
#include "hook.h"
#include "libmlx.h"
#include "tex.h"

int	check_size(char **map, int *cols, int *rows)
{
  int	i;
  int	j;

  *cols = 0;
  *rows = 0;
  if (map)
    {
      i = 0;
      j = 0;
      while (map[i][j])
	++j;
      *cols = j;
      while (map[i])
	++i;
      *rows = i;
    }
  return (0);
}

int	char_to_tex(char c)
{
  if (c == CHAR_WALL)
    return (0);
  if (c == CHAR_MONSTER)
    return (1);
  if (c == CHAR_LADDER)
    return (2);
  if (c == CHAR_INPUT)
    return (3);
  if (c == CHAR_OUTPUT)
    return (4);
  if (c == CHAR_KEY)
    return (5);
  return (-1);
}

int	img_calc(t_p *p)
{
  int	i;
  int	j;
  int	t;

  fill_img(&p->i, 0xFFBBFF);
  i = 0;
  while (i < p->rows)
    {
      j = 0;
      while (j < p->cols)
	{
	  if ((t = char_to_tex(p->map[i][j])) != -1)
	    img_to_img(&p->tex[t], &p->i, j * CASE, i * CASE);
	  ++j;
	}
      ++i;
    }
  return (0);
}

int	my_mlx(char **map)
{
  t_p	p;

  if ((p.map = map) == 0)
    return (0);
  check_size(map, &p.cols, &p.rows);
  p.sx = p.cols * CASE;
  p.sy = p.rows * CASE;
  if (p.sx < 3 || p.sy < 3 || (p.mlx = mlx_init()) == 0)
    return (puts("Error: fail to start mlx"));
  if ((p.w.win = mlx_new_window(p.mlx, (p.w.sx = p.sx), (p.w.sy = p.sy),
				(p.w.title = TITLE))) == 0)
    return (puts("Error: fail to open window"));
  if ((p.i.img = mlx_new_image(p.mlx, (p.i.sx = p.sx), (p.i.sy = p.sy))) == 0)
    return (puts("Error: fail to build image"));
  if (textures_loader(&p) == -1)
    return (puts("Error: fail to load textures"));
  p.i.data = mlx_get_data_addr(p.i.img, &p.i.bpp, &p.i.sl, &p.i.endian);
  img_calc(&p);
  mlx_expose_hook(p.w.win, &expose_hook, &p);
  mlx_key_hook(p.w.win, &key_hook, &p);
  mlx_mouse_hook(p.w.win, &mouse_hook, &p);
  mlx_loop_hook(p.mlx, &loop_hook, &p);
  return (mlx_loop(p.mlx));
}
